<template>
  <el-card shadow="hover">
    <div slot="header">
      <span>异常参数预警</span>
      <el-button 
        size="mini" 
        @click="getWarning" 
        style="float: right"
        :loading="loading"
      >
        <i class="el-icon-refresh"></i> 刷新 
      </el-button>
    </div>
    <el-table 
      :data="warning" 
      :header-cell-style="{background:'#f5f7fa'}" 
      border 
      class="weather-station-table"
      v-loading="loading"
    >
      <el-table-column prop="fd_id" label="设备ID" align="center"></el-table-column>
      <el-table-column prop="area" label="区域" align="center"></el-table-column>
      <el-table-column prop="state" label="预警参数" align="center"></el-table-column>
      <el-table-column prop="value" label="数值" align="center"></el-table-column>
      <el-table-column label="设备状态" align="center" width="120">
        <template #default="{row}">
          <el-tag :type="getDeviceStatus(row.fd_id)  === 'normal' ? 'success' : 'danger'">
            {{ getDeviceStatus(row.fd_id)  === 'normal' ? '正常' : '异常' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>
 
<script>
import { Loading } from 'element-ui'
 
export default {
  directives: {
    loading: Loading.directive  
  },
  data() {
    return {
      warning: [], // 预警信息 
      devices: [], // 设备列表 
      update: null, // 定时器 
      loading: false, // 加载状态 
      warningConfig: [
        { type: "soil", params: [
          { name: "土壤湿度超标", unit: "%RH", normalRange: [30, 70] },
          { name: "氮肥浓度不足", unit: "mg/L", normalRange: [15, 25] },
          { name: "PH值异常", unit: "", normalRange: [6, 7.5] }
        ]},
        { type: "water", params: [
          { name: "水压不足", unit: "MPa", normalRange: [0.2, 0.5] },
          { name: "水温过高", unit: "℃", normalRange: [15, 25] }
        ]}
      ]
    }
  },
  created() {
    this.getDevices(); 
  },
  methods: {
    async getDevices() {
      this.loading  = true;
      try {
        const response = await this.axios.get('http://localhost:55561/api/devices'); 
        this.devices  = response.data; 
        this.generateWarnings(); 
      } catch (error) {
        console.error(' 获取设备数据失败:', error);
        this.devices  = [
          {"id":"FD-2025-001","name":"1号土壤监测点","type":"soil","area":"东区种植基地","status":"normal","lastUpdate":"2025-04-08T19:21:35","weatherData":[]},
          {"id":"FD-2025-003","name":"2号土壤监测点","type":"soil","area":"西区温室大棚","status":"normal","lastUpdate":"2025-04-08T19:21:35","weatherData":[]},
          {"id":"FD-2025-007","name":"3号土壤监测点","type":"soil","area":"南区试验田","status":"warning","lastUpdate":"2025-04-08T19:21:35","weatherData":[]},
          {"id":"FD-2025-009","name":"5号土壤监测点","type":"soil","area":"中区滴灌区","status":"normal","lastUpdate":"2025-04-08T19:21:35","weatherData":[]},
          {"id":"FD-2025-012","name":"4号土壤监测点","type":"soil","area":"北区育苗室","status":"normal","lastUpdate":"2025-04-08T19:21:35","weatherData":[]}
        ];
        this.generateWarnings(); 
      } finally {
        this.loading  = false;
      }
    },
    generateWarnings() {
      this.warning  = this.devices.map(device  => {
        const config = this.warningConfig.find(c  => c.type  === device.type)  || this.warningConfig[0]; 
        const param = config.params[Math.floor(Math.random()  * config.params.length)]; 
        const isAbnormal = Math.random()  < 0.3;
        let value = isAbnormal 
          ? (Math.random()  > 0.5 
              ? param.normalRange[1]  + Math.random()  * 20 
              : param.normalRange[0]  - Math.random()  * 10)
          : param.normalRange[0]  + Math.random()  * (param.normalRange[1]  - param.normalRange[0]); 
        
        value = value.toFixed(param.unit  === '℃' || param.unit  === '' ? 1 : 2);
        
        return {
          fd_id: device.id, 
          area: device.area, 
          state: param.name, 
          value: `${value}${param.unit}` 
        };
      });
    },
    getDeviceStatus(deviceId) {
      const device = this.devices.find(d  => d.id  === deviceId);
      return device ? device.status  : 'unknown';
    },
    getWarning() {
      this.getDevices(); 
    }
  },
  activated() {
    this.update  = setInterval(() => {
      this.getWarning(); 
    }, 10000);
  },
  deactivated() {
    clearInterval(this.update); 
  }
}
</script>
 
<style scoped>
.weather-station-table {
  width: 100%;
}
</style>